<template>
  <el-dialog class="dialogT" width="600" :model-value="dialogVisible" :title="dialogDatas.title"
    :destroy-on-close="true" @close="closeDialog">
    <div>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm"
        :disabled="dialogDatas?.type == 'check'" :validate-on-rule-change="false">
        <!-- <el-form-item label="检测点ID" prop="id" v-if="dialogDatas.title=='新增' ? 1 :false">
          <el-input v-model="ruleForm.id" placeholder="请输入检测点ID" clearable maxlength="10" />
        </el-form-item> -->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile" @input="validatePhoneNumber" :disabled="dialogDatas?.type == 'edit'"
            placeholder="必须填写已经注册的手机号" clearable maxlength="11" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="根据手机号带出数据" disabled clearable />
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age" placeholder="根据手机号带出数据" disabled clearable />
        </el-form-item>

        <el-form-item label="性别" prop="genderName">
          <el-input v-model="ruleForm.genderName" placeholder="根据手机号带出数据" disabled clearable />
        </el-form-item>
        <el-form-item label="预约机构" prop="orgId" v-if="showOrg">
          <el-select :disabled="dialogDatas?.type === 'edit'" v-model="ruleForm.orgId" @change="changetOrg"
            class="w-full" placeholder="请选择归属机构">
            <el-option v-for="(item) in orgIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约检测点" prop="checkPointId">
          <el-select :disabled="dialogDatas?.type === 'edit'" v-model="ruleForm.checkPointId" @change="changeCheckId"
            placeholder="请选择" class="w-full">
            <el-option v-for="(item) in checkIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="reserveTime">
          <el-col class="w-full celanerTime" @click="openCalendar"
            :class="{ disableType: dialogDatas?.type == 'check' }">
            <span v-if="!ruleForm.reserveTime" style="color: #999;">请选择预约时间</span>
            <span v-else> {{ ruleForm.reserveTime.length > 18 ? ruleForm.reserveTime.slice(0,-3): ruleForm.reserveTime }}</span>
            <span class="caceder_icon"></span>
          </el-col>
        </el-form-item>
        <el-form-item label="检测方式" prop="checkType">
          <el-select v-model="ruleForm.checkType" @change="changeType" placeholder="请选择" class="w-full">
            <el-option label="到点检测" value="1" />
            <el-option label="顾问上门" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测点地址" v-show="ruleForm.checkType == '1'">
          <el-text class="mx-1">{{ ruleForm.area + (ruleForm.detailedAddress || '') }}</el-text>
        </el-form-item>
        <el-form-item label="上门顾问" v-show="ruleForm.checkType == '2'" prop="healthId">
          <el-select v-model="ruleForm.healthId" placeholder="请选择" class="w-full">
            <el-option :label="item.healthName" v-for="item in healthList" :value="item.healthId"
              :key="item.healthId" />
          </el-select>
        </el-form-item>
        <el-form-item label="上门地址" v-show="ruleForm.checkType == '2'" prop="address">
          <el-input v-model="ruleForm.address" placeholder="最多输入30字" class="w-full" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" maxlength="100" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    <el-dialog class="calendar" title="请选择预约日期" :model-value="calendarVisible" width="430" @close="closedCalendar">
      <div class="box">
        <el-calendar ref="calendar" v-model="calendarDate" class="calendarBox">
          <template #header="{ date }">
            <el-button size="small" @click="selectDate('prev-month')">
              上月
            </el-button><span>{{ date }}</span><el-button size="small" @click="selectDate('next-month')">
              下月
            </el-button>
          </template>
          <template #date-cell="{ data }">
            <div
              :class="!enDisabledDate.includes(data.day) ? 'disabledDate' : data.isSelected ? 'dateItem is-selected ' : 'dateItem'">
              <span>{{ data.day.split('-').slice(1)[1] }}</span>
              <!-- {{ data.isSelected ? '✔️' : '' }} -->
              <!-- <span style="font-size: 10px;" >{{ enDisabledDate.includes(data.day) ? '可约' : '' }}</span> -->
              <span :class="enDisabledDate.includes(data.day) ? 'point' : ''"></span>
            </div>
          </template>
        </el-calendar>
        <div class="times">
          <div class="time_box" v-for="(item, index) in times" :key="index" @click="changeTime(index)">
            <div :class="currentTimeIndex === index ? 'time active' : 'time'">{{ item }}</div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer" style="display: block;text-align: center;">
          <el-button @click="cancelCalendar">取消</el-button>
          <el-button type="primary" @click="entryCalendar">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>
<script lang="ts" setup>
import { watch, ref, reactive, onBeforeMount, toRefs, nextTick } from 'vue';
import { orgOptionsRequest } from '@/api/common';
import {
  getCheckPointsRequest,
} from '@/api/checkPoint';
import {
  format
} from '@/utils/util.js'
import type { FormInstance, FormRules } from 'element-plus';
import { getUserList } from '@/api/user';
import { getCalendar, getCheckHealth, AddPageRequest, AddPageRequestPut } from '@/api/appointment';

import type { CalendarDateType, CalendarInstance } from 'element-plus'
const calendar = ref(null)
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return
  if (val === 'next-month') {
    // 判断下月数据 有无可选，有的话，就跳转到 可选那天
    const canUseDate: any[] = []
    console.log(calendarDate.value);
    let date = format(calendarDate.value, 'YYYY-MM-DD')
    enDisabledDate.value.forEach(item => {
      if (Number(item.slice(5, -3)) > Number(date.slice(5, -3))) {
        canUseDate.push(item)
      }
    })
    if (canUseDate.length > 0) {
      calendarDate.value = canUseDate[0]
    } else {
      ElMessage.error('下月无可选日期')
    }
  } else if (val === 'prev-month') {
    // 判断上月数据 有无可选，有的话，就跳转到 可选那天
    const canUseDate: any[] = []
    console.log(calendarDate.value);
    let date = format(calendarDate.value, 'YYYY-MM-DD')
    enDisabledDate.value.forEach(item => {
      if (Number(item.slice(5, -3)) < Number(date.slice(5, -3))) {
        canUseDate.push(item)
      }
    })
    if (canUseDate.length > 0) {
      calendarDate.value = canUseDate[0]
    } else {
      ElMessage.error('上月无可选日期')
    }
  } else {
    calendar.value.selectDate(val)
  }
}
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible', 'handleFormValue']);
const calendarDate = ref(format(new Date(), 'YYYY-MM-DD'))
const visible = ref(false);
const times = ref([] as any[])
const oldTimes = ref([] as any[])
const currentTimeIndex = ref(0)
const healthList = ref([] as any[])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const enDisabledDate = ref([])
const calendarVisible = ref(false)
const openCalendar = async () => {
  if (dialogDatas.value?.type == 'check') {
    return
  }
  if (!ruleForm.checkPointId) {
    ElMessage.warning('请先选择检测点')
    return
  }


  await getCalendarF(ruleForm.checkPointId)

  calendarVisible.value = true
}

const CalendarDateList = ref([])
const getCalendarF = async (e: any) => {
  // 获取日历
  await getCalendar(e).then(res => {
    enDisabledDate.value = res.data.filter((item: any) => item.reserve).map((item: any) => item.date)
    CalendarDateList.value = res.data
    const currentDate = format(new Date(), 'YYYY-MM-DD')
    if (ruleForm.reserveTime) {
      calendarDate.value = ruleForm.reserveTime.split(' ')[0]
    } else {
      calendarDate.value = currentDate
    }
    if (calendarDate.value == currentDate) {
      times.value = CalendarDateList.value.find(item=> item.date === currentDate).workTimeList
      // const hours = format(new Date(), 'HH')
      // times.value = oldTimes.value.filter(item => {
      //   return hours < item.split(':')[0]
      // })
    }
    
    // 判断当前 预约日期 + 时间是否在可预约内，如果是 不做处理。如果不是则换成 最近的一次预约时间。
    if (enDisabledDate.value.includes(calendarDate.value)) {
      // 预约日期在当 可以预约内 同时times可选
      if (times.value.length === 0) {
        calendarDate.value = enDisabledDate.value[0]
        changeTime(0)
      }
    } else {

      calendarDate.value = enDisabledDate.value[0]
      changeTime(0)
    }

    if (calendarDate.value == currentDate) {
      times.value = CalendarDateList.value.find(item=> item.date === currentDate).workTimeList
    }
    nextTick(() => {
      times.value.forEach((e, i) => {
        if (e === ruleForm.reserveTime.split(' ')[1]) {
          changeTime(i)
        }
      });
    })
  })
}
const closedCalendar = () => {
  calendarVisible.value = false
}

const cancelCalendar = () => {
  closedCalendar()
}
const changeTime = (index: any) => {
  currentTimeIndex.value = index
}
const entryCalendar = () => {
  ruleForm.reserveTime = format(calendarDate.value, 'YYYY-MM-DD') + ' ' + times.value[currentTimeIndex.value]
  ruleFormRef.value?.clearValidate()
  closedCalendar()
}
const checkIdDatas = ref([] as any[])
const changetOrg = (e: any) => {
  // 根据机构获取检测点数据
  ruleForm.checkPointId = ''
  ruleForm.healthId = ''
  ruleForm.reserveTime = ''
  calendarDate.value = new Date()
  currentTimeIndex.value = 0
  getCheckedList(e)

}
const changeCheckId = (e: any) => {

  ruleForm.healthId = ''
  ruleForm.reserveTime = ''
  calendarDate.value = new Date()
  currentTimeIndex.value = 0
  checkIdDatas.value.forEach(item => {
    if (item.id === e) {
      ruleForm.area = item.area
      ruleForm.detailedAddress = item.detailedAddress
    }
  })
  getHealth(e)
}
const getCheckedList = (e: any) => {
  getCheckPointsRequest({
    pageSize: 999,
    pageNum: 1,
    orgId: e
  }).then(res => {
    checkIdDatas.value = res.data.list.map((item: any) => {
      return {
        id: item.id,
        name: item.pointName,
        area: item.area,
        detailedAddress: item.detailedAddress,

      }
    })
    if (ruleForm.checkPointId) {
      checkIdDatas.value.forEach(item => {
        if (item.id === ruleForm.checkPointId) {
          ruleForm.area = item.area
          ruleForm.detailedAddress = item.detailedAddress
        }
      })
    }

  })
}
const getHealth = (e: any) => {
  getCheckHealth(e).then((res: any) => {
    healthList.value = res.data
  })
}

const changeType = (e: any) => {
  if (e == 1) {
    rules.healthId[0].required = false
    rules.address[0].required = false
  } else {
    rules.healthId[0].required = true
    rules.address[0].required = true
  }
  ruleFormRef.value?.clearValidate()
}
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
let ruleForm = reactive({
  reserveId: null,
  name: null,
  orgId: '',
  reserveTime: "",
  checkType: '',
  healthId: '',
  address: "",
  remark: "",
  mobile: "",
  checkPointId: '',
  age: '',
  genderName: '',
  area: '',
  detailedAddress: '',

})
// let chanFormValue = reactive({});
watch(calendarDate, (newValue, oldValue) => {
  console.log(newValue, oldValue,'-================================');
  
  const cDate = format(new Date(), 'YYYY-MM-DD')
  if (!oldValue || !newValue) {
    calendarDate.value = enDisabledDate.value[0]
    return
  }
  const currentDate = format(newValue, 'YYYY-MM-DD')
  const oldDate = format(oldValue, 'YYYY-MM-DD')
  if (!enDisabledDate.value.includes(currentDate)) {
    if(!enDisabledDate.value.includes(oldDate)) {
      return
    }
    // 当天不在可选日期则不做处理
    if (cDate === oldDate) {
      return
    } else {
      // 这里是不给选 不在可约日期范围内的数据
      calendarDate.value = oldDate
      return
    }

  }
  currentTimeIndex.value = 0
  times.value = CalendarDateList.value.find(item=> item.date === currentDate).workTimeList
  // if (currentDate === format(new Date(), 'YYYY-MM-DD')) {
  //   times.value = CalendarDateList.value.find(item=> item.date === currentDate).workTimeList
  // } else {
  //   times.value = [...oldTimes.value]
  // }

  // calendarDate.value = new Date('2024-07-30')

});
// 校验
const rules = reactive<FormRules>({
  mobile: [{ required: true, message: '必须填写已经注册的手机号', trigger: 'blur' },],
  name: [{ required: true, message: '', trigger: 'blur' },],
  age: [{ required: true, message: '', trigger: 'blur' },],
  genderName: [{ required: true, message: '', trigger: 'blur' },],
  checkPointId: [{ required: true, message: '请选择检测点', trigger: 'change' }],
  orgId: [{ required: true, message: '选择归属组织', trigger: 'change' }],
  status: [{ required: true, message: '选择状态', trigger: 'change' }],
  districtId: [{ required: true, message: '选择所在地区', trigger: 'change' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
  reserveTime: [{ required: true, message: '请选择预约时间', trigger: 'blur' }],
  checkType: [{ required: true, message: '请选择检测方式', trigger: 'change' }],
  healthId: [{ required: true, message: '请选择上门顾问', trigger: 'change' }],
  address: [{ required: true, message: '请填写上门地址', trigger: 'blur' }],
  // { validator: checkAge, trigger: 'blur' }
})


function validatePhoneNumber(event: any) {
  // 限制只能输入数字
  ruleForm.mobile = event.replace(/\D/g, '');
  if (ruleForm.mobile.length === 11) {
    getuser(ruleForm.mobile)
  } else {
    ruleForm.age = ''
    ruleForm.genderName = ''
    ruleForm.name = null
  }


}
const getuser = (e: any) => {
  getUserList({
    pageSize: 10,
    pageNum: 1,
    searchWords: e
  }).then(res => {
    const data = res.data.list[0]
    if (!data) {
      ElMessage.error('这个用户还未注册，请先到用户管理中添加此用户')
      return
    }
    ruleForm.age = data?.age
    ruleForm.genderName = data?.genderText || ''
    ruleForm.name = data?.name || ''

  })
}
//提交
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let Url = dialogDatas.value.type == 'add' ? AddPageRequest : AddPageRequestPut;
      if (ruleForm.reserveTime.split(' ')[1].split(':').length < 3) {
        ruleForm.reserveTime = ruleForm.reserveTime + ':00'
      }
      // let res: any = await Url(ruleForm);
      // if (res.code === 2000) {
      //   ElMessage.success('保存成功')
      //   emit("update:dialogVisible", false);
      // } else {
      //   ruleForm.reserveTime = ruleForm.reserveTime.slice(0, -3)
      //   ElMessage.error(res.message + '13123132')
      // }
      try {
        let res: any = await Url(ruleForm);
        console.log(res);
        
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);

        formEl.resetFields()//重置
        emit('updateList')
      } catch (error) {
        ruleForm.reserveTime = ruleForm.reserveTime.slice(0, -3)
      }
    } else {
      console.log('保存失败', fields)
    }
  })
}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}
// 归属机构下拉
let orgIdDatas = reactive([] as any[])
let showOrg = ref(true)
const getOrgOptionsDatas = async () => {
  showOrg.value = false
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
  showOrg.value = true
};

onBeforeMount(async () => {
  getOrgOptionsDatas()
  if (dialogDatas.value.type == 'add') {
  } else {
    ruleForm = Object.assign(ruleForm, dialogDatas.value.datas)
    ruleForm.reserveTime = ruleForm.reserveTime.slice(0, -3)
    ruleForm.checkType = String(ruleForm.checkType)
    if (ruleForm.healthId == 0) {
      ruleForm.healthId = ''
    }
    changeType(ruleForm.checkType)
    getHealth(ruleForm.checkPointId)
    getCheckedList(ruleForm.orgId)
    getCalendarF(ruleForm.checkPointId)
  }
})
</script>

<style lang="scss" scoped>
.celanerTime {
  height: 32px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  text-indent: 10px
}

.disableType {
  color: #a8abb2;
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.el-dialog__footer {
  text-align: center;
}

.cell {
  padding: 3px 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.cell .text {
  width: 24px;
  margin: 0 auto 4px;
}

.cell.current {
  background: #626aef;
  color: #fff;
  border-radius: 6px;

  .text {
    color: #fff
  }
}

.cell .holiday {
  position: absolute;
  width: 6px;
  height: 6px;
  background: var(--el-color-danger);
  border-radius: 50%;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
}

.cell span {
  line-height: 12px;
}

.box {
  display: flex;
  flex-direction: column;

  .calendarBox {
    width: 400px;
  }

  .times {
    display: flex;
    width: 400px;
    flex-wrap: wrap;
    padding: 0 7px;
    box-sizing: border-box;
    margin-top: 10px;

    .time_box {
      width: 20%;
      padding: 5px;
      box-sizing: border-box;
    }

    .time {
      width: 100%;
      box-sizing: border-box;
      height: 30px;
      line-height: 30px;
      text-align: center;
      font-size: 12px;
      border-radius: 6px;
      border: 1px solid #eee;
      cursor: pointer;

      &.active {
        color: #FFC200;
        border: 1px solid #FFC200;
        background: #FFF9E5;
      }
    }
  }
}

.caceder_icon {
  position: absolute;
  right: 10px;
  top: 5px;
  width: 18px;
  height: 18px;
  background: url('@/assets/image/cacel_icon.png') center center no-repeat;
  background-size: cover;
}
</style>
<style lang="scss">
.dialogT {
  .el-date-editor.el-input {
    width: 100%;
  }

  .el-calendar-table .el-calendar-day {
    height: 48px;
    text-align: center;
  }
}

.calendar {

  .el-dialog__body {
    padding: 0;
  }

  .el-calendar__body {
    padding: 12px;
    border-bottom: 1px solid #eee;
  }

  .el-calendar-day {
    padding: 0;
    font-size: 14px;
  }

  .el-calendar-table td {
    border: none !important;
  }
}

.el-calendar-table td.is-selected {
  background-color: #ffc200;
  border-radius: 6px;
  font-size: 14px;

  .point {
    display: block;
    width: 4px;
    height: 4px;
    background-color: #666;
    border-radius: 4px;
  }
}

.disabledDate {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: gray;
  height: 48px;
  font-size: 14px;
}

.dateItem {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 48px;
  color: #000
}

.point {
  display: block;
  width: 4px;
  height: 4px;
  background-color: #19BE6B;
  border-radius: 4px;
}
</style>